#!/usr/bin/env python3.9
# coding: utf-8
import sys,getopt
import asyncio
import websockets
import json
import base64
import wave

HELP_STRING='audio2face_server.py -s <server ip> -p <server port>'
WAV_PATH="./wav/{}.wav"

def write_wav(qsid,voice):
    """
    将收到音频数据写成WAV的文件
    """
    file_path=WAV_PATH.format(qsid)
    file_data= base64.b64decode(bytes(voice, encoding="utf8"))    
    print("rev wav data to file :"+file_path)
    f=open(file_path,mode='bx')
    f.write(file_data)
    f.close()
    return file_path
    
async def recv_msg(websocket):
    """
    接收客户端消息并处理，这里只是简单把客户端发来的返回回去
    """
    while True:        
        try:
            recv_text = await websocket.recv()            
            request_data=json.loads(recv_text)
            if request_data["text"] is not None and request_data["qsid"] is not None:
                print("request rev qsid:{}  text:{}".format( request_data["qsid"], request_data["text"]))
            if request_data["voice"] is not None:
                #写接到音频文件以qsid命名写到wav文件里面                
                file_path=write_wav(request_data["qsid"],request_data["voice"] )        
                #可以在这里调用Audio2Face

            response_text = f"your submit context: {recv_text}"
            await websocket.send(response_text)
        except:
            pass
        
async def main_logic(websocket, path):
    """
    服务器端主逻辑
    websocket和path是该函数被回调时自动传过来的，不需要自己传
    """
    await recv_msg(websocket)


if __name__ == '__main__':
    server="127.0.0.1"
    port=5555
    try:
        opts, args = getopt.getopt(sys.argv[1:],"-h-s:-p:",["help","server=","port="])
    except getopt.GetoptError:
        print(HELP_STRING)
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print(HELP_STRING)
            sys.exit()
        elif opt in ("-s", "--server"):
            server=arg
        elif opt in ("-p", "--port"):
            port=arg

    print("start server ip:{}  port:{}  ......".format(server,port))
    start_server = websockets.serve(main_logic, server, port)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()